require 'semantictext/span'
require 'semantictext/tag'

require 'string'
require 'semantictext/default_tag_factory'

module SemanticText
 
  # I parse chunks of text into a sequence of spans, tags and urls. 
  class RichTextParser

    # I need a tag_factory on which I can call create_tag(name, content_text) to create my tags.
    def initialize(tag_factory)
      @tag_factory = tag_factory
    end

    private
  
    def create_tag(regex, source)
      source =~ regex
      tag_name = $1
      tag_value = $2
      @tag_factory.create_tag(tag_name, tag_value)
    end
    
    def parse_text_for_urls(text, enclosing_element)
  	    link_next = false
  	    ignore_next_section = false
  	    sections = text.split /((http|ftp|mailto):[^ ]*)/
  	    if sections[0]==''
  	      ignore_next_section = true
  	      link_next = true
  	    end
  	    sections.each do |section|
  	        if (ignore_next_section)
  	          ignore_next_section = false
  	        else
  	          if (link_next)
  	            enclosing_element << create_tag(/([^:]+):([^\]]*)/, section)
  	            ignore_next_section = true            
  	          else
  	            enclosing_element << Span.new(section)
  	          end
  	          link_next = !(link_next)
  	        end
  	    end    
  	end

    public
    
    # I parse a line of text, pushing the elements into enclosing_element as I find them.
    def parse(line, enclosing_element)
      sections = line.split /(\[[^:]+:[^\]]+\])/
      tag_next = false
      sections.each do |section|
        if (tag_next)
          enclosing_element << create_tag(/\[([^:]+):([^\]]*)\]/, section)
        else
          parse_text_for_urls(section, enclosing_element)
        end
        tag_next = !(tag_next)
      end
    end

  end
end
